﻿using eslib.FileManageLib;
using eslib.HttpApiClient;
using eslib.tools.config;
using Newtonsoft.Json;
using NLog;

namespace ArticleClientLib
{
    /// <summary>
    /// 从服务器同步的Article（用于ArticleSyncSystem）
    /// </summary>
    public class SyncArticle
    {
        ILogger logger = LogManager.GetCurrentClassLogger();
        void Info(string msg) => logger.Info(msg);
        void Error(string msg) => logger.Error(msg);

        private long id;
        private string[] images;
        private string main;
        private ArticleJson ArtJson;
        private Classifly classifly;

        public SyncArticle(Classifly c, ArticleSyncJson json)
        {
            id = json.id;
            images = json.GetImages();
            main = json.GetMain();
            ArtJson = json.ToArticleJson();
            classifly = c;
        }



        string Dir
            => Path.Combine(classifly.Root, $"{id}");

        string getPath(string file)
        {
            return Path.Combine(Dir, file);
        }


        /// <summary>
        /// 保存到分类目录下，并构造所有目录结构
        /// </summary>
        /// <param name="c"></param>
        public async Task Save()
        {
            //确保Dir目录
            DirCopier.CreateDir(Dir);

            //images目录
            DirCopier.CreateDir(getPath("images"));

            //保存doc.json
            JsonSerializerSettings setting = new()
            {
                Formatting = Formatting.Indented,
            };
            GenericJsonConfig.Save(ArtJson, getPath("doc.json"), setting);


            //下载main.png
            await downImage(main, Dir);

            //下载内容图片
            foreach (var img in images)
                await downImage(img, getPath("images"));
        }



        async Task downImage(string url, string dir)
        {
            try
            {
                ApiClient api = new(url);
                var (success, image) = await api.DownImageAsync();
                if (!success) throw new Exception("DownImage时异常");

                string path = Path.Combine(dir, Path.GetFileName(url));
                File.WriteAllBytes(path, image);
            }
            catch (Exception ex)
            {
                Error($"下载图片[{url}]时异常:{ex.Message}");
            }
        }


    }
}
